package pxe

import (
	jwt "github.com/dgrijalva/jwt-go"
	"github.com/kataras/iris/v12"
	"time"
)

func Middleware(ctx iris.Context) {
	////token, _ := CreateJWTToken("0001", "admin", "mu tong qi huang niu")
	////ctx.Header("Authorization", token)
	//tokenAuth := ctx.FormValue("auth")
	//if _, err := ParseToken(tokenAuth, "mu tong qi huang niu"); err != nil {
	//	ctx.StatusCode(503)
	//	return
	//}
	ctx.Next()
}

func CreateJWTToken(uid, admin, secret string) (string, error) {
	at := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"uid":  uid,
		"name": admin,
		"exp":  time.Now().Add(time.Hour * 10000).Unix(),
	})
	token, err := at.SignedString([]byte(secret))
	if err != nil {
		return "", err
	}
	return token, nil
}

func ParseToken(token string, secret string) (string, error) {
	claim, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})
	if err != nil {
		return "", err
	}
	return claim.Claims.(jwt.MapClaims)["uid"].(string), nil
}
